#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define BUFFER_SIZE 5

int buffer[BUFFER_SIZE];
int count = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER; // 条件变量：缓冲区非空
pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;  // 条件变量：缓冲区未满

void *producer(void *arg)
{
    for (int i = 0; i <= 10; i++)
    {
        pthread_mutex_lock(&lock);
        while (count == BUFFER_SIZE)
        {
            pthread_cond_wait(&not_full, &lock); // 缓冲区满等待
        }
        buffer[count++] = i;
        printf("工厂生产：%d\n", i);
        pthread_cond_signal(&not_empty); //  通知消费者有产品可消费
        pthread_mutex_unlock(&lock);
        usleep(100000); // 模拟生产时间(0.1秒)
    }
    return NULL;
}

void *consumer(void *arg)
{
    for (int i = 0; i <= 10; i++)
    {
        pthread_mutex_lock(&lock);
        while (count == 0)
        {
            pthread_cond_wait(&not_empty, &lock); // 缓冲区空等待
        }
        int item = buffer[--count]; // 从缓冲区取出产品
        printf("顾客消费：%d\n", item);
        pthread_cond_signal(&not_full); // 通知生产者有空位可生产
        pthread_mutex_unlock(&lock);
        usleep(100000); // 模拟消费时间
    }

    return NULL;
}

int main()
{
    pthread_t p, c;
    pthread_create(&p, NULL, producer, NULL);
    pthread_create(&c, NULL, consumer, NULL);
    pthread_join(p, NULL);
    pthread_join(c, NULL);
    return 0;
}